package com.chuyu.cy.ws;

import com.chuyu.cy.entity.moudle.Message;
import com.chuyu.cy.exception.CustomException;
import com.google.gson.Gson;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: white-zhou
 * @date: 2024-03-26 19:44
 **/
@ServerEndpoint("/socket/chat/{userId}")
public class SocketToChat {

    private Integer userId;

    private static ConcurrentHashMap<Integer,Session> sessionPool =
            new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        try {
            this.userId = userId;
            sessionPool.put(userId,session);
        } catch (Exception e) {
            System.out.println("onOpen error:" + e.getMessage());
        }

    }


    @OnMessage
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(String message) {
        try {
            Gson gson = new Gson();
            Message msg = gson.fromJson(message, Message.class);
            if (msg.getSenderId() == null || msg.getReceiverId() == null) {
                throw new CustomException("senderId or receiverId is null");
            }
            sendMessage(msg.getReceiverId(), message);
        } catch (Exception e) {
            System.out.println("onOpen error:" + e.getMessage());
        }
    }


    public static void sendMessage(Integer receiverId, String message) {
        try {
            Session session = sessionPool.get(receiverId);
            if (session != null && session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            System.out.println("onOpen error:" + e.getMessage());
        }
    }



    @OnClose
    public void onClose() {
        try {
            sessionPool.remove(this.userId);
        } catch (Exception e) {
            System.out.println("onOpen error:" + e.getMessage());
        }
    }
}
